<?php
declare (strict_types = 1);

namespace app\user\controller;

use app\common\controller\BaseController;
use app\common\model\Config;
use app\user\model\User;

class Login extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    /*
     * 账号密码登录/短信登录
     */
    public function login()
    {
        $model = new User();
        $data = $model->login($this->user->id);
        if($data == false && !empty($model->error))
            return retu_json(400, $model->error, []);
        return retu_json(200, '操作成功', $data);
    }

    /*
     * 小程序登录，登录成功后生成token令牌
     */
    public function wxLogin($code)
    {
        $bool = false;
        $boolToken =  input('server.HTTP_AUTHORIZATION');
        // 如果没有token  或者 code
        if(!$code && !$boolToken)
            return retu_json(400, '登录信息不完整');
        #有token 先根据token进行校验
        if(!empty($boolToken)){
            $this->token = $boolToken;
            $bool = $this->checkToken();
            if($bool === true){
                $this->user = (new User())->field($this->field)->where(['id'=>$this->mid?:0, 'is_delete'=>0])->find();
                if(empty($this->user)) return retu_json(400, '用户信息异常，请联系客服！');
                else{
                    $data = $this->user->toArray();
                    $data['nickname'] = $data['nickName'];
                    $data['token'] = $boolToken;
                    // 更新最近登录时间
                    User::where('id',$this->user['id'])->update([
                        'last_time' => time()
                    ]);
                    unset($data['session_key']);
                }
            }
        }
        #无token 或者 token已过期，根据code调用微信登录接口
        if($bool !== true){
            if(empty($code)) return retu_json(400, '无code');
            $config = $this->getConfig();
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['appsecret'].'&js_code='.$code.'&grant_type=authorization_code';
            $info= json_decode(curlGet($url), true);
            if (!$info)
                return retu_json(400, 'code失效');
            if(!isset($info['session_key']) || !isset($info['openid']))
                return retu_json(400, '获取微信数据失败', $info);
            $userModel = new User();
            // 调用此处的验证信息
            $data =  $userModel->loginCode($info);
            if($data === false) return retu_json(400, $userModel->error, []);
        }

        return retu_json(200, '操作成功', $data);
    }

    /*
     * 修改用户密码（登录前）
     */
    public function modifyPass()
    {
        $model = new User();
        $data = $model->modifyPass();
        if($data == false && !empty($model->error))
            return retu_json(400, $model->error, []);
        return retu_json(200, '操作成功', $data);
    }

    /*
     * 更新用户密码（登录后）
     */
    public function updatePass()
    {
        $model = new User();
        $data = $model->updatePass($this->user->id);
        if($data == false && !empty($model->error))
            return retu_json(400, $model->error, []);
        return retu_json(200, '操作成功', $data);
    }

    //获取小程序配置
    private function getConfig(){
        $model = new Config();
        return $model->toData('wechat');
    }
}
